<template>
  <view class="profile-page">
    <!-- 用户信息区域 -->
    <view class="user-section" @click="handleLogin">
      <view class="user-avatar">
		  <uni-id-pages-avatar disabled v-if="userInfo.avatar_file" style="border-radius: 50%;"  width="140rpx" height="140rpx" mode="aspectFill"></uni-id-pages-avatar>
		  <image v-else :src="userInfo.avatar?userInfo.avatar:'/static/logo.png'" mode="aspectFill"/>
      </view>
      <view class="user-info">
        <text class="user-name">{{ userInfo.nickname || userInfo.userName|| '点击登录' }}</text>
        <text class="user-desc">登录后使用更多功能</text>
      </view>
      <view class="icon icon-right" style="font-size: 20px; color: #999;">›</view>
    </view>
    
    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-group">
        <view class="menu-item" @click="navigateToFavorites">
          <view class="menu-icon">
            <view class="icon icon-heart" style="font-size: 24px; color: #ff4d4f;">❤️</view>
          </view>
          <text class="menu-text">我的收藏</text>
          <view class="menu-right">
            <text class="menu-badge">{{ favoriteCount || '' }}</text>
            <view class="icon icon-right" style="font-size: 18px; color: #999;">›</view>
          </view>
        </view>
        
        <view class="menu-item" @click="navigateToDownloads">
          <view class="menu-icon">
            <view class="icon icon-download" style="font-size: 24px; color: #52c41a;">⬇️</view>
          </view>
          <text class="menu-text">下载历史</text>
          <view class="menu-right">
            <text class="menu-badge">{{ downloadCount || '' }}</text>
            <view class="icon icon-right" style="font-size: 18px; color: #999;">›</view>
          </view>
        </view>
      </view>
      
      <view class="menu-group">
        <view class="menu-item" @click="navigateToFeedback">
          <view class="menu-icon">
            <view class="icon icon-chatbubble" style="font-size: 24px; color: #1890ff;">💬</view>
          </view>
          <text class="menu-text">意见反馈</text>
          <view class="icon icon-right" style="font-size: 18px; color: #999;">›</view>
        </view>
        
        <view class="menu-item" v-if="uniCloud.getCurrentUserInfo()role.includes('manage')" @click="navigateToAdmin">
          <view class="menu-icon">
            <view class="icon icon-settings" style="font-size: 24px; color: #722ed1;">⚙️</view>
          </view>
          <text class="menu-text">管理员入口</text>
          <view class="icon icon-right" style="font-size: 18px; color: #999;">›</view>
        </view>
      </view>
      
      <view class="menu-group">
        <view class="menu-item" @click="handleClearCache">
          <view class="menu-icon">
            <view class="icon icon-trash" style="font-size: 24px; color: #faad14;">🗑️</view>
          </view>
          <text class="menu-text">清除缓存</text>
          <text class="cache-size">{{ cacheSize }}</text>
        </view>
        
        <view class="menu-item" @click="navigateToAbout">
          <view class="menu-icon">
            <view class="icon icon-info" style="font-size: 24px; color: #8c8c8c;">ℹ️</view>
          </view>
          <text class="menu-text">关于我们</text>
          <text class="version">v1.0.0</text>
        </view>
      </view>
    </view>
    
    <!-- 退出登录按钮 -->
    <view class="logout-section" v-if="isLoggedIn">
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import {onLoad, onShow} from "@dcloudio/uni-app"

// 状态管理
const userInfo = ref({
  nickname: '',
  avatar_file: ''
});
const isLoggedIn = ref(false);
const favoriteCount = ref(0);
const downloadCount = ref(0);
const cacheSize = ref('0KB');
const defaultAvatar = 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/user.png';

onShow(() => {
  checkLoginStatus();
  getCacheSize();
  if (isLoggedIn.value) {
    getUserStats();
  }
});

// 检查登录状态
const checkLoginStatus = () => {
  try {
    const userToken = uni.getStorageSync('uni_id_token');
    const savedUserInfo = uni.getStorageSync('uni-id-pages-userInfo');
    
    if (userToken && savedUserInfo) {
      isLoggedIn.value = true;
      userInfo.value = savedUserInfo;
    } else {
      isLoggedIn.value = false;
      userInfo.value = {
        nickname: '',
        avatar_file: ''
      };
      favoriteCount.value = 0;
      downloadCount.value = 0;
    }
  } catch (error) {
    console.error('检查登录状态失败:', error);
    // 出错时确保状态一致
    isLoggedIn.value = false;
    userInfo.value = {
      nickname: '',
      avatar_file: ''
    };
    favoriteCount.value = 0;
    downloadCount.value = 0;
  }
};

// 获取用户统计数据
const getUserStats = async () => {
  try {
    // 获取当前token
    const userToken = uni.getStorageSync('uni_id_token');
    console.log('调用usergetStats云函数，token状态:', { hasToken: !!userToken });
    
    // 尝试调用云函数获取统计数据
    try {
      const res = await uniCloud.callFunction({
        name: 'usergetStats',
        data: {
          uniIdToken: userToken
        }
      });
      
      console.log('getUserStats云函数调用结果:', res.result);
      
      if (res && res.result) {
        if (res.result.code === 0) {
          favoriteCount.value = res.result.data.favoriteCount;
          downloadCount.value = res.result.data.downloadCount;
        } else if (res.result.code === 401) {
          console.log('获取统计数据认证失败，token状态:', res.result.tokenStatus);
          
          // 如果是token过期或错误，尝试刷新token
          if (res.result.tokenStatus === 'expired' || res.result.tokenStatus === 'error') {
            console.log('token可能过期，尝试重新加载token...');
            const newToken = uni.getStorageSync('uni_id_token'); // 尝试重新获取
            if (newToken && newToken !== userToken) {
              // 如果token已更新，重试一次
              console.log('发现新token，重试获取统计数据...');
              getUserStats();
              return;
            }
            // 否则清除登录状态
            checkLoginStatus();
          } else {
            // 其他401错误，检查登录状态
            checkLoginStatus();
          }
        } else {
          console.log('获取统计数据失败:', res.result.message);
        }
      } else {
        console.log('usergetStats云函数调用返回异常',res);
      }
    } catch (cloudError) {
      console.error('云函数调用失败:', cloudError);
    }
  } catch (error) {
    console.error('获取统计数据失败1:', error);
    // favoriteCount.value = Math.floor(Math.random() * 20);
    // downloadCount.value = Math.floor(Math.random() * 50);
  }
};

// 获取缓存大小
const getCacheSize = () => {
  try {
    // 尝试获取实际缓存大小
    try {
      // 实际项目中可能会调用特定API获取缓存大小
      // 这里为了演示使用模拟数据
      cacheSize.value = '1.2MB';
    } catch (cacheError) {
      console.log('获取实际缓存大小失败，使用默认值:', cacheError);
      cacheSize.value = '0KB';
    }
  } catch (error) {
    console.error('获取缓存大小失败:', error);
    // 最终兜底，确保数据有值
    cacheSize.value = '0KB';
  }
};

// 处理登录
const handleLogin = () => {
  // if (isLoggedIn.value) return;
  
  uni.navigateTo({
    // url: '/pages/login/login'
    url: '/uni_modules/uni-id-pages/pages/userinfo/userinfo'
  });
};

// 处理退出登录
const handleLogout = () => {
  uni.showModal({
    title: '退出登录',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 与uni-id用户体系保持一致的存储键名
        uni.removeStorageSync('uni_id_token');
        uni.removeStorageSync('uni-id-pages-userInfo');
        
        // 清除可能存在的其他用户信息缓存
        uni.removeStorageSync('userInfo');
        
        checkLoginStatus();
        uni.showToast({ title: '已退出登录', icon: 'success' });
      }
    }
  });
};

// 清除缓存
const handleClearCache = () => {
  uni.showModal({
    title: '清除缓存',
    content: '确定要清除所有缓存吗？',
    success: (res) => {
      if (res.confirm) {
        // 模拟清除缓存
        setTimeout(() => {
          cacheSize.value = '0KB';
          uni.showToast({ title: '缓存已清除', icon: 'success' });
        }, 500);
      }
    }
  });
};

// 导航到收藏页面
const navigateToFavorites = () => {
  if (!isLoggedIn.value) {
    handleLogin();
    return;
  }
  uni.navigateTo({ url: '/pages/favorite/favorite' });
};

// 导航到下载历史
const navigateToDownloads = () => {
  const userToken = uni.getStorageSync('uni_id_token');
  if (!userToken) {
    uni.navigateTo({
      url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
    });
    return;
  }
  uni.navigateTo({ url: '/pages/download/download' });
};

// 导航到反馈页面
const navigateToFeedback = () => {
  uni.navigateTo({ url: '/pages/feedback/feedback' });
};

// 导航到管理员页面
const navigateToAdmin = () => {
	const uidinfo=uniCloud.getCurrentUserInfo()
	console.log('自带用户信息uidinfo',uidinfo);
	if(!uidinfo.role.includes('manager')){
		uni.showToast({
			title:"您不是管理员！",
			icon:'none'
		})
	}
  uni.navigateTo({ url: '/pages/admin/login' });
};

// 导航到关于页面
const navigateToAbout = () => {
  uni.navigateTo({ url: '/pages/about/about' });
};
</script>

<style scoped lang="less">
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.profile-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .user-section {
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 20px 16px;
    margin-bottom: 12px;
    .user-avatar {
      width: 60px;
      height: 60px;
      border-radius: 30px;
      overflow: hidden;
      margin-right: 16px;
      image {
        width: 100%;
        height: 100%;
      }
    }
    .user-info {
      flex: 1;
      .user-name {
        display: block;
        font-size: 18px;
        font-weight: 500;
        color: #333;
        margin-bottom: 4px;
      }
      .user-desc {
        display: block;
        font-size: 14px;
        color: #999;
      }
    }
  }
  
  .menu-section {
    .menu-group {
      background-color: #fff;
      margin-bottom: 12px;
      .menu-item {
        display: flex;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid #f0f0f0;
        &:last-child {
          border-bottom: none;
        }
        .menu-icon {
          width: 32px;
          text-align: center;
          margin-right: 16px;
        }
        .menu-text {
          flex: 1;
          font-size: 16px;
          color: #333;
        }
        .menu-right {
          display: flex;
          align-items: center;
          .menu-badge {
            color: #999;
            font-size: 14px;
            margin-right: 8px;
          }
        }
        .cache-size,
        .version {
          color: #999;
          font-size: 14px;
          margin-right: 8px;
        }
      }
    }
  }
  
  .logout-section {
    padding: 20px 16px;
    button {
      background-color: #fff;
      color: #f5222d;
      border: none;
      border-radius: 8px;
      padding: 12px;
      font-size: 16px;
    }
  }
}
</style>